package cmd

import (
	"embed"
	"html/template"
	"log"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/spf13/cobra"
)

var (
	//go:embed resources/*
	efs   embed.FS
	cache Meta
)

// Meta 页面元信息
type Meta struct {
	Imgs           []Image
	Previous, Next int
}

// Image 图片元信息
type Image struct {
	Auth string
	Name string
	Path string
}

// serveCmd represents the serve command
var serveCmd = &cobra.Command{
	Use:   "serve",
	Short: "图片展示",
	Long:  `实验性功能`,
	Run: func(cmd *cobra.Command, args []string) {
		picRoot := "pics"
		http.Handle("/", http.FileServer(http.Dir(path.Join("."))))
		http.HandleFunc("/pics", func(rw http.ResponseWriter, r *http.Request) {
			page, offset := 0, 72
			page, _ = strconv.Atoi(r.URL.Query().Get("pg"))
			f, err := template.ParseFS(efs, "resources/*.tmpl")
			if err != nil {
				log.Fatalln("模板读取错误", err)
			}
			meta := walker(picRoot)
			meta.Previous = page - 1
			meta.Next = page + 1
			res := meta.Imgs
			st, en := page*offset, page*offset+offset
			if en > len(res) {
				en = len(res)
				st = en - offset
			}
			meta.Imgs = meta.Imgs[st:en]
			f.Execute(rw, meta)
		})
		err := http.ListenAndServe("0.0.0.0:8080", nil)
		if err != nil {
			log.Fatalln(err)
		}
	},
}

func init() {
	rootCmd.AddCommand(serveCmd)
}

func walker(src string) Meta {
	if len(cache.Imgs) != 0 {
		return cache
	}
	res := make([]Image, 0)
	filepath.Walk(filepath.Join(src), func(path string, info os.FileInfo, err error) error {
		if info.IsDir() {
			return nil
		}
		res = append(res, Image{filepath.Dir(path), info.Name(), strings.ReplaceAll(path, "\\", "/")})
		return nil
	})
	cache = Meta{Imgs: res}
	return cache
}
